package cn.edu.jnu.basicms.mapper;

import cn.edu.jnu.basicms.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    // 新增用户
    @Insert("INSERT INTO user (username, password, name, phone, email, address, avatar) " +
            "VALUES (#{username}, #{password}, #{name}, #{phone}, #{email}, #{address}, #{avatar})")
    void insert(User user);

    // 修改用户（根据ID）
    @Update("UPDATE user SET username=#{username}, password=#{password}, name=#{name}, " +
            "phone=#{phone}, email=#{email}, address=#{address}, avatar=#{avatar} WHERE id=#{id}")
    void updateUser(User user);

    // 删除单个用户（根据ID）
    @Delete("DELETE FROM user WHERE id=#{id}")
    void deleteUser(Integer id);

    // 查询所有用户（带排序）
    @Select("SELECT * FROM user ORDER BY id DESC")
    List<User> selectAll();

    // 根据ID单条件查询单个用户
    @Select("SELECT * FROM user WHERE id=#{id}")
    User selectById(Integer id);

    // 根据姓名模糊查询
    @Select("SELECT * FROM user WHERE name LIKE CONCAT('%', #{name}, '%')")
    List<User> selectByName(String name);

    // 多条件查询
    @Select("<script>" +
            "SELECT * FROM user " +
            "WHERE 1 = 1 " +
            "<if test='username != null and username != \"\"'>" +
            "AND username LIKE CONCAT('%', #{username}, '%') " +
            "</if>" +
            "<if test='name != null and name != \"\"'>" +
            "AND name LIKE CONCAT('%', #{name}, '%') " +
            "</if>" +
            "<if test='phone != null and phone != \"\"'>" +
            "AND phone LIKE CONCAT('%', #{phone}, '%') " +
            "</if>" +
            "<if test='email != null and email != \"\"'>" +
            "AND email LIKE CONCAT('%', #{email}, '%') " +
            "</if>" +
            "<if test='address != null and address != \"\"'>" +
            "AND address LIKE CONCAT('%', #{address}, '%') " +
            "</if>" +
            "</script>")
    List<User> selectByMultipleConditions(Map<String, Object> conditions);

    // 分页模糊查询
    @Select("SELECT * FROM user WHERE name LIKE CONCAT('%', #{name}, '%') LIMIT #{offset}, #{pageSize}")
    List<User> selectByPageAndName(@Param("name") String name, @Param("offset") int offset, @Param("pageSize") int pageSize);

    // 查询满足条件的总记录数
    @Select("SELECT COUNT(*) FROM user WHERE name LIKE CONCAT('%', #{name}, '%')")
    long countByPageAndName(@Param("name") String name);
}